﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MiniScrum.Models
{
    public class Role
    {
        public int Id { get; set; }
        public string RoleName { get; set; }
        public virtual ICollection<User> Users { get; set; }

        public Role()
        {
            Users = new HashSet<User>();
        }

        public static UserRolesModel GetUserRoles(int userId)
        {
            using (var db = new MiniScrumDB())
            {

                User user = db.Users.Find(userId);
                List<Role> roles = db.Roles.ToList();

                return new UserRolesModel(roles, user.Roles.Select(r => (r.Id.ToString())).ToList(), user);

            }
        }

        public static void SaveUserRoles(UserRolesModel model)
        {
            using (var db = new MiniScrumDB())
            {
                User u = db.Users.Find(model.UserId);

                u.Roles.Clear();
                model.Selected.ToList().ForEach(r =>
                {
                    Role role = db.Roles.Find(int.Parse(r));
                    u.Roles.Add(role);
                });

                db.SaveChanges();
            }
        }
    }
}